// 初始化全局变量

let shopInfo = {
  mallId: '',
  mallName:''
};

// 从本地存储获取mallId

function getMallId() {
  try {
    //const mallId = localStorage.getItem('mall-info-id') || localStorage.getItem('agentseller-mall-info-id');
    const isTemu = window.location.href.includes('temu.com');
    console.log('[Content] getMallId:', isTemu);
    const mallId = isTemu
        ? localStorage.getItem('agentseller-mall-info-id')
        : localStorage.getItem('mall-info-id');
    if (mallId && mallId !== shopInfo.mallId) {
      console.log('[Content] 检测到mallId变化，更新shopInfo:', mallId);
      // 发送消息到background script请求最新的商店列表
      chrome.runtime.sendMessage({
        action: 'getShopInfo',
        oldMallId: shopInfo.mallId,
        newMallId: mallId
      });

      shopInfo.mallId = mallId;
    } else if (!mallId) {
      console.error('无法从本地存储获取店铺ID');
    }
  } catch (error) {
    console.error('获取店铺ID时出错:', error);
  }
}
// 添加storage事件监听器
window.addEventListener('storage', (e) => {
  console.log('[Content] 存储事件:', e.key);
  //if (e.key === 'mall-info-id') {
  getMallId();
  // }
});

// 添加页面URL变化监听
let lastUrl = window.location.href;
new MutationObserver(() => {
  const currentUrl = window.location.href;
  if (currentUrl !== lastUrl) {
    console.log('[Content] 检测到页面URL变化');
    lastUrl = currentUrl;
    getMallId();
  }
}).observe(document, {subtree: true, childList: true});
//访问userinfo获取信息
// 添加标签页可见性变化监听
document.addEventListener('visibilitychange', () => {
  console.log('[Content] 检测到标签页状态变化:', document.visibilityState);
  if (document.visibilityState === 'visible') {
    console.log('[Content] 标签页变为可见，重新获取店铺信息');
    getMallId();
  }
});

// ... existing code ...
// 初始化时获取mallId

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'initRegistration') {
    handleActivityRegistration(request.activityId, request.activityType, request.minPrice,request.priceType,request.priceData,request.antiContent,request.activityStock);
    sendResponse({success: true}); // 在 Manifest V3 中，最好总是发送响应
  } else if (request.action === 'fetchUserInfo') {
    // 在内容脚本中执行userInfo请求
    fetchUserInfo(request.antiContent,request.newMallid);
    sendResponse({success: true}); // 在 Manifest V3 中，最好总是发送响应
  } else if (request.action === 'updateShopInfo') {
    console.log('[Content] updateShopInfo收到消息:', request);
    // 更新本地shopInfo
    if (request.shopInfo) {

      shopInfo = {
        mallId: request.shopInfo.mallId,
        mallName: request.shopInfo.mallName
      };
      console.log('[Content] updateShopInfo店铺信息已更新:', shopInfo);


    }
    sendResponse({success: true}); // 在 Manifest V3 中，最好总是发送响应
  } else if(request.action === 'fetchProductsPageFromContent') {
    fetchProductsPageFromContent(request.url, request.data,request.antiContent);
    sendResponse({success: true}); // 在 Manifest V3 中，最好总是发送响应
  } else if(request.action === 'fetchActivityListFromContent') {
    fetchActivityListFromContent(request.url, request.antiContent)
        .then(data => {
          sendResponse({success: true, data: data});
        })
        .catch(error => {
          sendResponse({success: false, error: error.message});
        });
    return true; // 保持异步响应开放
  }

  return true; // 保
});
// 在内容脚本中执行userInfo请求

async function fetchUserInfo(antiContentParam,newMallid) {
  try {

    // 使用传入的antiContent参数，如果没有则使用全局变量
    const antiContentToUse = antiContentParam ;
    const newMallidToUse = newMallid ;
    console.log('[Content] 开始请求用户信息...newMallidToUse:', newMallidToUse);
    console.log('[Content] 开始请求用户信息...使用antiContent:', antiContentToUse);

    if (!antiContentToUse) {
      console.error('[Content] 缺少Anti-Content参数，无法请求用户信息');
      return;
    }
    // 根据当前页面URL确定API基础地址
    const baseUrl = window.location.href.includes('agentseller-us')
        ? 'https://agentseller-us.temu.com/api/seller/auth/userInfo' //美国地址
        : 'https://agentseller.temu.com/api/seller/auth/userInfo';
    // 发送请求
    const response = await fetch(baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Anti-Content': antiContentToUse,
        'Cookie': document.cookie,
        'Origin': window.location.href,
        'Referer': window.location.href,
      },
      body: JSON.stringify({needCanEnrollCnt:true})
    });

    const data = await response.json();
    console.log('[Content] 用户信息请求成功:', data);

    // 将响应发送回background script
    chrome.runtime.sendMessage({
      action: 'userInfoResponse',
      data: data,
      newMallid:newMallidToUse ||''

    });
  } catch (error) {
    console.error('[Content] 获取用户信息失败:', error);// 即使失败也发送消息回去
    chrome.runtime.sendMessage({
      action: 'userInfoResponse',
      error: error.message
    });
  }
}
//下载活动记录
// 获取活动列表数据
async function fetchActivityListFromContent(url, antiContentParam) {
  try {
    // 使用传入的antiContent参数
    const antiContentToUse = antiContentParam;

    updateStatus('开始获取活动列表数据...');

    if (!antiContentToUse) {
      updateStatus('缺少Anti-Content参数，使用空值');
    }

    // 获取活动列表
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Anti-Content': antiContentToUse || '',
        'Cookie': document.cookie,
        'MallId': shopInfo?.mallId || '',
        'Origin': 'https://agentseller.temu.com',
        'Referer': window.location.href,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin'
      },
      body: JSON.stringify({needCanEnrollCnt:true})
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const responseData = await response.json();
    //console.log('[Content] 获取活动列表数据成功:', responseData);

    return responseData;
  } catch (error) {
    console.error('[Content] 获取活动列表数据失败:', error);
    updateStatus('获取活动列表数据失败: ' + error.message);
    throw error;
  }
}

//下载活动记录
async function fetchProductsPageFromContent(url, data, antiContentParam) {
  try {
    // 使用传入的antiContent参数
    const antiContentToUse = antiContentParam;

    updateStatus('开始获取活动商品数据...');

    if (!antiContentToUse) {
      updateStatus(' 缺少Anti-Content参数，使用空值');
    }

    // 获取商品列表
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Anti-Content': antiContentToUse || '',
        'Cookie': document.cookie,
        'MallId': shopInfo?.mallId || '',
        'Origin': 'https://agentseller.temu.com',
        'Referer': window.location.href,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin'
      },
      body: JSON.stringify(data)
    });
    console.log('con获取活动商品数据 response:', JSON.stringify(response));
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const responseData = await response.json();
    console.log('[Content] 获取活动商品数据成功');

    // 将响应发送回background script
    //chrome.runtime.sendMessage({
    // action: 'fetchProductsPageResponse',
    // data: responseData
    //});

    return responseData;
  } catch (error) {
    updateStatus('获取活动商品列表失败:'+ error);

  }
}

// 更新状态函数
function updateStatus(message) {
  console.log('[Content] 状态更新:', message);
  try {
    chrome.runtime.sendMessage({
      action: 'updateStatus',
      message: message
    });
  } catch (error) {
    console.error('[Content] 发送状态更新失败:', error);
  }
}

// 处理活动报名流程
async function handleActivityRegistration(thematicId, activityType, minPrice,priceType,priceData,antiContentParam,activityStock) {
  try {
    let totalProducts = 0;
    let failedProducts = 0;
    let hasMore = true;
    let searchScrollContext = '';

    updateStatus(`开始活动报名流程，活动ID: ${thematicId}, 类型: ${activityType}, 不报名的最低价格: ${minPrice}`);
    // 使用传入的antiContent参数，如果没有则使用全局变量
    const antiContentToUse = antiContentParam ;
    updateStatus('开始获取商品列表，每页最多50个商品');
    while (hasMore) {
      // 获取商品列表
      const response = await fetch('https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/semi/scroll/match', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': '*/*',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Anti-Content': antiContentToUse,
          'Cookie': document.cookie,
          'MallId': shopInfo?.mallId || '',
          'Origin': 'https://agentseller.temu.com',
          'Referer': window.location.href,
          'Sec-Fetch-Dest': 'empty',
          'Sec-Fetch-Mode': 'cors',
          'Sec-Fetch-Site': 'same-origin',

        },
        body: JSON.stringify({
          activityType: parseInt(activityType),
          activityThematicId: parseInt(thematicId),
          rowCount: 50,
          addSite: true,
          ...(searchScrollContext && { searchScrollContext })
        })
      });

      const data = await response.json();
      if (!data.success) {
        throw new Error('获取商品列表失败');
      }

      updateStatus(`获取到商品列表，本页商品数: ${data.result.matchList.length}`);
      //console.log('[Content] 获取商品列表数据成功:', data);
      // 处理商品列表数据
      const productList = processProducts(data.result.matchList, priceType, priceData, minPrice, activityStock);
      //console.log('[Content] 处理后的商品列表:', productList);
      if (productList.length === 0) {
        updateStatus('本页没有符合条件的商品，继续下一页');
      }
      else {
        // 一次性获取所有商品的场次信息
        const productIds = productList.map(product => product.productId);

        updateStatus(`准备获取${productIds.length}个商品的场次信息`);
        // 一次性获取所有商品的场次信息

        const sessionResponse = await fetch('https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/session/list', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Anti-Content': antiContentToUse,
            'Cookie': document.cookie,
            'MallId': shopInfo?.mallId || '',
            'Origin': 'https://agentseller.temu.com',
            'Referer': window.location.href,
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin'
          },
          body: JSON.stringify({
            productIds: productList.map(product => product.productId),
            activityType: parseInt(activityType),
            activityThematicId: parseInt(thematicId)
          })
        });


        const sessionData = await sessionResponse.json();
       // console.log('[Content] 获取场次信息 response:', JSON.stringify(sessionData));
        if (sessionData.success) {
          // 为每个商品分配对应的场次ID
          let validProductCount = 0;
          for (const product of productList) {
            const sessions = sessionData.result.productCanEnrollSessionMap[product.productId];
            if (sessions && sessions.length > 0) {
              product.sessionIds = sessions.map(session => session.sessionId);
              validProductCount++;
            } else {
              updateStatus(`商品 ${product.productId} 没有可用场次，将跳过`);
              // 从列表中移除没有场次的商品
              const index = productList.indexOf(product);
              if (index > -1) {
                productList.splice(index, 1);
              }
            }
          }

          updateStatus(`共有${validProductCount}个商品有可用场次，准备一次性提交`);

          // 一次性提交所有商品
          if (productList.length > 0) {
            let retryCount = 0;
            const maxRetries = 2;
            const retryDelay = 15000; // 10秒延时

            while (retryCount <= maxRetries) {
              try {
                if (retryCount > 0) {
                  updateStatus(`批量提交失败，等待${retryDelay/1000}秒后第${retryCount}次重试...`);
                  await new Promise(resolve => setTimeout(resolve, retryDelay));
                }

                updateStatus(`开始批量提交${productList.length}个商品`);
                const submitResponse = await fetch('https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/semi/submit', {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/json',
                    'Accept': '*/*',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Anti-Content': antiContentToUse,
                    'Cookie': document.cookie,
                    'MallId': shopInfo?.mallId || '',
                    'Origin': 'https://agentseller.temu.com',
                    'Referer': window.location.href,
                    'Sec-Fetch-Dest': 'empty',
                    'Sec-Fetch-Mode': 'cors',
                    'Sec-Fetch-Site': 'same-origin'
                  },
                  body: JSON.stringify({
                    activityType: parseInt(activityType),
                    activityThematicId: parseInt(thematicId),
                    productList: productList
                  })
                });

                const submitResult = await submitResponse.json();
                totalProducts += productList.length;

                console.log(`批量提交结果: ${JSON.stringify(submitResult)}`);
                if (submitResult.success) {
                  updateStatus(`批量提交成功！本次提交${productList.length}个商品 (总成功数: ${totalProducts - failedProducts}/总报名数: ${totalProducts})`);
                  break;
                } else {
                  if (submitResult.errorCode === 2000000 && retryCount < maxRetries) {
                    retryCount++;
                    continue;
                  }
                  const failCount = productList.length;
                  failedProducts += failCount
                  totalProducts += failCount; // 失败的也要计入总数
                  updateStatus(`批量提交失败: ${submitResult.errorMsg || '未知错误'}`);
                  break;
                }
              } catch (error) {
                if (retryCount < maxRetries) {
                  retryCount++;
                  updateStatus(`批量提交出错，第${retryCount}次重试`);
                  continue;
                }
                failedProducts += productList.length;

                updateStatus(`批量提交出错: ${error.message || '未知错误'}`);
                break;
              }
            }
          } else {
            updateStatus('没有可用商品进行提交，跳过本页');
          }
        } else {
          updateStatus(`获取场次信息失败: ${sessionData.errorMsg || '未知错误'}`);
        }
      }

      // 更新分页信息
      if (data.result.searchScrollContext) {
        searchScrollContext = data.result.searchScrollContext;
        hasMore = data.result.hasMore;
        if (!hasMore) {
          updateStatus(`已到达最后一页，报名流程即将结束,(总成功数: ${totalProducts - failedProducts}/总报名数: ${totalProducts})`);
        } else {
          updateStatus(`更新分页信息，是否有更多: ${hasMore}, 新的上下文: ${searchScrollContext ? '已获取' : '无'}`);
        }
      } else {
        hasMore = false;
      }

      // 发送进度更新
      chrome.runtime.sendMessage({
        action: 'registrationStatus',
        total: totalProducts,
        failed: failedProducts,
        hasMore: hasMore
      });
      if (hasMore) {
        const randomDelay =  Math.floor(Math.random() * (45000 - 15000 + 1)) + 15000;
        const waitSeconds = Math.floor(randomDelay / 1000);
        updateStatus(`等待 ${waitSeconds} 秒后获取下一页商品...`);
        //updateStatus('等待后获取下一页商品...');

        await new Promise(resolve => setTimeout(resolve, randomDelay));
      }
    }

    // console.log(`报名完成！总计：${totalProducts}，失败：${failedProducts}`);
  } catch (error) {
    updateStatus('报名过程出错：', error);
    chrome.runtime.sendMessage({
      action: 'registrationStatus',
      error: error.message
    });
  }
}



// 添加商品处理方法
function processProducts(matchList, priceType, priceData, minPrice, activityStock) {
  //console.log('添加商品处理方法'+JSON.stringify(matchList))
  return matchList
      .filter(item => {
        const priceThreshold = (minPrice || 3.6) * 100;

        // 根据价格设置方式进行筛选
        if (priceType === '1') {
          const fixedPrice = minPrice * 100;
          //console.log('添加商品处理2方法'+JSON.stringify(item.activitySiteInfoList))
          return item.activitySiteInfoList.every(site =>
              site.skcList.every(skc =>

                  skc.suggestActivityPrice >= fixedPrice
              )
          );
        } else if (priceType === '2') {
          const minRandomPrice = priceData.minRandomPrice * 100;
          return item.activitySiteInfoList.every(site =>
              site.skcList.every(skc =>
                  skc.suggestActivityPrice >= minRandomPrice
              )
          );
        }
        //console.log('添加商品处理3方法'+JSON.stringify(item.activitySiteInfoList))
        return item.activitySiteInfoList.every(site =>
            site.skcList.every(skc =>
                skc.suggestActivityPrice >= priceThreshold)

        );
      })
      .map(item => ({
        productId: item.productId,
        activityStock: activityStock !== undefined ? item.suggestActivityStock + activityStock : item.suggestActivityStock,
        siteInfoList: item.activitySiteInfoList.map(site => ({
          siteId: site.siteId,
          skcList: site.skcList.map(skc => {
            let finalPrice = skc.suggestActivityPrice

            if (priceType === '1') {
              finalPrice = minPrice * 100;
            } else if (priceType === '2') {
              const maxRandomPrice = priceData.maxRandomPrice * 100;
              if (finalPrice >= maxRandomPrice) {
                finalPrice = maxRandomPrice;
              }
            }
            return {
              skcId: skc.skcId,
              activityPrice: finalPrice,
              skuList: skc.skuList.map(sku => ({skuId: sku.skuId}))
            };
          }),

        }))
      }))
}


